package org.fly.api.common.core.support.validator.handle;



import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.fly.api.common.core.support.validator.anno.EnumCheck;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


/**
 * 枚举校验处理
 * @author Blue
 * @date 2023/11/06
 */
@Slf4j
public class EnumCheckValidator implements ConstraintValidator<EnumCheck, Object> {

    private List<String> values = new ArrayList<>();

    @Override
    public void initialize(EnumCheck enumCheck) {
        Class<?> clazz = enumCheck.value();
        Object[] constants = clazz.getEnumConstants();
        try {
            Method method = clazz.getMethod(enumCheck.method());
            Object val;
            for (Object constant : constants) {
                val = method.invoke(constant);
                values.add(Convert.toStr(val));
            }
        }catch (Exception e){
            log.error("EnumCheckValidator error", e);
        }
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        //true 检验通过，false校验不通过
        return ObjectUtil.isNull(value) || values.contains(Convert.toStr(value));
    }
}

